<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar '+postForm.status">
        <el-button v-waves v-if="postForm.id" style="margin-left: 10px;" type="success" @click="updateUser">{{ $t('table.edit') }}</el-button>
        <el-button v-waves v-else style="margin-left: 10px;" type="success" @click="insertUser">{{ $t('table.add') }}</el-button>
        <el-button v-waves v-if="postForm.isFreeze === 1 && postForm.id" type="success" @click="freezeStatus(postForm, 0)">{{ $t('table.thaw') }}</el-button>
        <el-button v-waves v-else-if="postForm.isFreeze === 0 && postForm.id" type="warning" @click="openFreeze(postForm,1)">{{ $t('table.freeze') }}</el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('table.nickname')" prop="nickname">
              <el-input v-model="postForm.nickname"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-top: 35px">
            <el-button v-waves @click="random">{{ $t('form.randoms') }}</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('table.phone')" prop="phone">
              <el-input v-model="postForm.mobile"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-top: 35px">
            <el-form-item :label="$t('table.sex')" prop="sex">
              <el-radio-group v-model="postForm.sex">
                <el-radio label="0">{{ $t('form.female') }}</el-radio>
                <el-radio label="1">{{ $t('form.male') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-top: 35px">
            <el-form-item :label="$t('form.birthday')">
              <el-date-picker
                v-model="postForm.birthday"
                :placeholder="$t('form.date')"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col v-if="postForm.id" :span="8">
            <el-form-item :label="$t('table.creationtime')" prop="sex">
              <el-date-picker
                v-model="postForm.creationTime"
                :disabled="false"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="创建时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('table.infractions')" >
              <el-input-number v-model="postForm.infractions" :disabled="false" :min="0" :max="10"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('table.sign')">
          <el-input
            :placeholder="$t('form.sign')"
            v-model="postForm.sign"
            type="textarea"
            maxlength="30"
            show-word-limit/>
        </el-form-item>

        <el-form-item :label="$t('form.avatar')">
          <div style="margin-bottom: 20px;">
            <Upload v-model="postForm.avatar" :userId="postForm.id"/>
          </div>
        </el-form-item>

      </div>
    </el-form>

  </div>
</template>

<script>
import Upload from '@/components/Upload/avatarUpload'
import Sticky from '@/components/Sticky' // 粘性header组件
import waves from '@/directive/waves' // 按钮波浪样式

import { getUserById, freezeStatusById, insertUser, updateUser } from '@/api/user'
import { toMessage, toNotify } from '@/utils/hint' // 提示信息
import { randomNickName } from '@/utils/randomNickName'
import { timeFormat } from '@/utils'

const defaultForm = {
  // s
  id: undefined,
  mobile: '', // 手机号
  nickname: '', // 昵称
  isFreeze: '', // 冻结状态
  infractions: '', // 违规次数
  sign: '', // 签名
  avatar: '', // 头像地址
  sex: '0', // 性别
  birthday: '', // 年龄
  creationTime: '', // 创建时间
  updateTime: '' // 修改时间
}

export default {
  name: 'UserDetail',
  components: { Upload, Sticky },
  directives: { waves },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // const isMobileNumber = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error(this.$t('msg.require') + this.$t('table.phone') + '1'))
    //   } else {
    //     const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
    //     const isPhone = reg.test(value)
    //     value = Number(value) // 转换为数字
    //     if (typeof value === 'number' && !isNaN(value)) { // 判断是否为数字
    //       value = value.toString() // 转换成字符串
    //       if (value.length < 0 || value.length > 12 || !isPhone) { // 判断是否为11位手机号
    //         callback(new Error(this.$t('form.phone') + '138xxxx8754'))
    //       } else {
    //         callback()
    //       }
    //     } else {
    //       callback(new Error(this.$t('msg.require') + this.$t('table.phone') + '2'))
    //     }
    //   }
    // }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        nickname: [
          { required: true, message: this.$t('msg.require') + this.$t('table.nickname'), trigger: 'blur' },
          { min: 3, max: 8, message: this.$t('msg.nickname'), trigger: 'blur' }
        ]
        // phone: [
        //   { required: true, message: this.$t('msg.require') + this.$t('table.phone'), trigger: 'blur' }
        //   { validator: isMobileNumber, trigger: 'blur'}
        // ]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length
    },
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // 如果是修改，则获取并显示数据
    fetchData(id) {
      getUserById(id).then(response => {
        this.postForm = response.data.extend.user
        this.postForm.sex = '' + response.data.extend.user.sex
        // Just for test
        this.postForm.id = response.data.extend.user.id

        // Set tagsview title
        this.setTagsViewTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    // 头部导航的显示
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑用户' : 'Edit User'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('updateVisitedView', route)
    },
    // 保存用户
    insertUser() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          // this.postForm.birthday = ('' + this.postForm.birthday).substring(0, 10)
          console.log(this.postForm.birthday)
          insertUser(this.postForm).then(response => {
            if (response.data.code === 200) {
              toNotify(this, 'success', '添加用户成功', '成功', 2000)
              this.loading = false
            } else {
              toNotify(this, 'error', '添加用户失败', '失败', 2000)
            }
          })
        } else {
          toNotify(this, 'warning', '请输入合法的数据', '警告', 2000)
          return false
        }
      })
    },
    // 修改用户
    updateUser() {
      this.postForm.creationTime = timeFormat(this.postForm.creationTime)
      this.postForm.birthday = this.postForm.birthday.substring(0, 10)
      this.postForm.updateTime = ''
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          updateUser(this.postForm).then(response => {
            if (response.data.code === 200) {
              toNotify(this, 'success', '修改用户成功', '成功', 2000)
            } else {
              toNotify(this, 'error', '修改用户失败', '失败', 2000)
            }
          }).catch(err => {
            console.log(err)
            toNotify(this, 'error', '修改用户失败', '失败', 2000)
          })
        } else {
          toNotify(this, 'warning', '请输入合法的数据', '警告', 2000)
          return false
        }
      })
    },
    // 冻结提示
    openFreeze(row, status) {
      this.$confirm('此操作将冻结该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.freezeStatus(row, status)
      }).catch(() => {
        toMessage(this, 'info', '已取消冻结')
      })
    },
    // 切换冻结状态
    freezeStatus(row, status) {
      const msg = status === 0 ? '解冻' : '冻结'
      freezeStatusById(row.id, status).then(response => {
        if (response.data.code === 200) {
          toMessage(this, 'success', msg + '成功!')
          this.postForm.isFreeze = status
        } else {
          toMessage(this, 'error', msg + '失败')
        }
      })
    },
    // 随机昵称
    random() {
      this.postForm.nickname = randomNickName(this.lang)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
    .editor-container {
      min-height: 500px;
      margin: 0 0 30px;
      .editor-upload-btn-container {
        text-align: right;
        margin-right: 10px;
        .editor-upload-btn {
          display: inline-block;
        }
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
